package com.wcpdoc.exam.core.util;

import cn.hutool.core.io.FileUtil;
import com.wcpdoc.core.exception.MyException;
import com.wcpdoc.exam.core.em.EmResourceType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;

/**
 * @Classname FileUtils
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/4/5 15:49
 * @Created by CALVIN
 */
public class FileUtils {

    /**
     * 存储文件到系统
     * @param file 文件,path 文件路径
     * @return 文件名
     */
    public static String storeFile(MultipartFile file, String path) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
        try {
            if(fileName.contains("..")) {
                throw new MyException("文件路径出错...." + fileName);
            }
            if(!FileUtil.exist(fileStorageLocation.getParent().toString())){
                FileUtil.mkdir(fileStorageLocation.getParent());
            }

            Path targetLocation = fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), fileStorageLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new MyException("存储文件失败 ...." + fileName + "请重试");
        }
    }
    /**
     * 加载文件
     * @param file_name 文件路径
     * @return 文件资源
     */
    public static Resource loadFileAsResource(String file_name) {
        try {
            Path filePath = Paths.get(file_name).toAbsolutePath().normalize();
            String fileName = filePath.getFileName().toString();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new MyException("文件不存在 " + fileName);
            }
        } catch (MalformedURLException ex) {
            throw new MyException("文件不存在 ....");
        }
    }
    /**
     * 根据文件后缀判断文件类型
     * @param fileName 文件名
     * @return 该文件所属类型
     */
    public static Integer transforType(String fileName) {
        if(fileName == null){
            fileName = "emptyFileName";
            return EmResourceType.其他.getCode();
        }else {
            //获取文件后缀名并转化为小写，用于后续比较
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
            //创建图片类型数组
            String img[] = { "bmp", "jpg", "jpeg", "png", "tiff", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd",
                    "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "wmf" };
            for(int i = 0; i < img.length; i++){
                if (img[i].equals(fileType)) {
                    return EmResourceType.图片.getCode();
                }
            }
            //创建文档类型数组
            String document[] = { "txt", "doc", "docx", "xls","xlsx", "htm", "html", "jsp", "rtf", "wpd", "pdf", "ppt"};
            for (int i = 0; i < document.length; i++) {
                if (document[i].equals(fileType)) {
                    return EmResourceType.文档.getCode();
                }
            }
            // 创建视频类型数组
            String video[] = { "mp4", "avi", "mov", "wmv", "asf", "navi", "3gp", "mkv", "f4v", "rmvb", "webm" };
            for (int i = 0; i < video.length; i++) {
                if (video[i].equals(fileType)) {
                    return EmResourceType.视频.getCode();
                }
            }
            // 创建音频类型数组
            String music[] = { "mp3", "wma", "wav", "mod", "ra", "cd", "md", "asf", "aac", "vqf", "ape", "mid", "ogg",
                    "m4a", "vqf" };
            for (int i = 0; i < music.length; i++) {
                if (music[i].equals(fileType)) {
                    return EmResourceType.音频.getCode();
                }
            }
        }
        return EmResourceType.其他.getCode();
    }
    /**
     * 根据文件字节大小，转换成相应的B,KB,MB,GB
     * @param size 文件的字节大小
     * @return 转换单位后的文件大小
     */
    public static String transforSize(long size) {
        //获取到的size bites，表示字节大小
        int GB = 1024 * 1024 * 1024;//定义GB的计算常量
        int MB = 1024 * 1024;//定义MB的计算常量
        int KB = 1024;//定义KB的计算常量
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        String resultSize = "";
        if (size / GB >= 1) {
            //如果当前Byte的值大于等于1GB
            resultSize = df.format(size / (float) GB) + "GB";
        } else if (size / MB >= 1) {
            //如果当前Byte的值大于等于1MB
            resultSize = df.format(size / (float) MB) + "MB";
        } else if (size / KB >= 1) {
            //如果当前Byte的值大于等于1KB
            resultSize = df.format(size / (float) KB) + "KB";
        } else {
            resultSize = size + "B";
        }
        return resultSize;
    }
    /**
     * 判断哪些是可以预览，也就是读取的文本文件
     * @param fileName 文件路径
     * @return 是否可以读取
     */
    public static boolean canPreView(String fileName) {
        //获取文件后缀名并转化为小写，用于后续比较
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
        // 创建可以预览文本类型数组
        String canPreviewArray[] = { "txt", "java", "xml", "py","lrc","sql","html","jsp"};
        for (int i = 0; i < canPreviewArray.length; i++) {
            if (canPreviewArray[i].equals(fileType)) {
                return true;
            }
        }
        return false;
    }
}


